# 备份es watcher,user,role,dashboar
##python elastic_backup.py -es=https://localhost:9200 -kibana=http://localhost:5601 -u=elastic -p=z3UVORWUwq7=5FA+4Him


import requests
import os
import datetime
import json
import argparse
import base64
class ElasticBasicBackup:
	kibana_url='http://localhost:5601'
	elastic_url='https://localhost:9200'
	basic_auth=''
	prefix=''
	savedir='tempbackup'
	def __init__(self,prefix):
		if prefix=="date":
			self.prefix = datetime.datetime.now().strftime('%Y-%m-%d')+"_"
	def download_watcher(self):
		pass
		res = requests.get(self.elastic_url+'/.watches/_search?size=1000',headers={
			"Authorization":"Basic "+self.basic_auth
			},verify= False)
		jsonres = res.text
		if res.status_code!=200:
			print('get watcher fail..')
			print(res)

			return
		parsed = json.loads(jsonres)
		total = parsed['hits']['total']['value']
		with open(os.path.join(self.savedir,self.prefix+'watches.json'),'w',encoding='utf-8') as f:
			f.write(json.dumps(parsed,indent=4))
		return total
	def download_user(self):
		pass
		res = requests.get(self.elastic_url+'/_security/user',headers={
			"Authorization":"Basic "+self.basic_auth
			},verify= False)
		jsonres = res.text
		parsed = json.loads(jsonres)
		total = len(parsed)
		with open(os.path.join(self.savedir,self.prefix+'user.json'),'w',encoding='utf-8') as f:
			f.write(json.dumps(parsed,indent=4))
		return total		
	def download_kibana_role(self):
		pass
		if not os.path.exists(self.savedir):
			print("creating dir "+self.savedir)
			os.makedirs(self.savedir)
		res = requests.get(self.kibana_url+'/api/security/role',headers={
			"Authorization":"Basic "+self.basic_auth
			})
		jsonres = res.text
		parsed = json.loads(jsonres)
		with open(os.path.join(self.savedir,self.prefix+'role.json'),'w',encoding='utf-8') as f:
			f.write(json.dumps(parsed,indent=4))
		return len(parsed)
	def download_dashboards(self):
		pass
		self.check_and_create_dir()
		res = requests.post(self.kibana_url+'/api/saved_objects/_export',data='{"type":["config","lens","index-pattern","visualization","dashboard","url","search","query","map","infrastructure-ui-source","metrics-explorer-view","inventory-view","canvas-element","canvas-workpad"],"includeReferencesDeep":true}'
			,headers={
			"kbn-xsrf":"true",
			"Authorization":"Basic "+self.basic_auth
			})
		jsonres = res.text
		with open(os.path.join(self.savedir,self.prefix+'dashboards.ndjson'),'w',encoding='utf-8') as f:
			f.write(jsonres)
	def check_and_create_dir(self):
		if not os.path.exists(self.savedir):
			print("creating dir "+self.savedir)
			os.makedirs(self.savedir)

	def download_searchtemplate(self):
		pass
		self.check_and_create_dir()
		res = requests.get(self.elastic_url+'/_cluster/state/metadata?pretty&filter_path=**.stored_scripts',headers={
			"Authorization":"Basic "+self.basic_auth
			},verify= False)
		jsonres = res.text
		# print('res',jsonres)
		parsed = json.loads(jsonres)
		total = len(parsed['metadata']['stored_scripts'])
		with open(os.path.join(self.savedir,self.prefix+'searchtemplate.json'),'w',encoding='utf-8') as f:
			f.write(json.dumps(parsed,indent=4))
		return total
	def download_transform(self):
		pass
		self.check_and_create_dir()
		res = requests.get(self.elastic_url+'/_transform/_all',headers={
			"Authorization":"Basic "+self.basic_auth
			},verify= False)
		jsonres = res.text
		# print('res',jsonres)
		parsed = json.loads(jsonres)
		# print(parsed)
		total = parsed['count']
		with open(os.path.join(self.savedir,self.prefix+'transform.json'),'w',encoding='utf-8') as f:
			f.write(json.dumps(parsed,indent=4))
		return total			
if __name__=="__main__":
	parser = argparse.ArgumentParser(description='Elastic Config Backup')

	parser.add_argument('-prefix','--prefix',default="date")
	parser.add_argument('-es', '--elastic_url', default='http://localhost:9200',
                    help='elastic url,not ends with /',required=True)
	parser.add_argument('-kibana', '--kibana_url', default='http://localhost:9200',
                    help='kibana url,not ends with /',required=True)
	parser.add_argument('-u', '--username', default='elastic',
                    help='elastic auth username',required=True)
	parser.add_argument('-p', '--password',
                    help='elastic auth password',required=True)
	parser.add_argument('-o', '--output',default='es_backup',
                    help='output dir')
	args = parser.parse_args()

	print('backup to dir='+args.output)
	backup = ElasticBasicBackup(args.prefix)
	backup.elastic_url=args.elastic_url
	backup.kibana_url=args.kibana_url
	backup.savedir=args.output
	backup.basic_auth=str(base64.b64encode((args.username+':'+args.password).encode("utf-8")),'utf-8')
	


	backup.download_dashboards()
	watchertotal = backup.download_watcher()
	usertotal = backup.download_user()
	kibana_role_total = backup.download_kibana_role()
	searchtemplate_total = backup.download_searchtemplate()
	transformTotal = backup.download_transform()
	# print('watcher total='+str(watchertotal))
	# print('user role total='+str(usertotal))
	# print('kibana role total='+str(kibana_role_total))
	# print('search template='+str(searchtemplate_total))
	# print('search template='+str(searchtemplate_total))
	print({
		"watcher":watchertotal,
		"user":usertotal,
		"kibanaRole":kibana_role_total,
		"searchTemplate":searchtemplate_total,
		"transformTotal":transformTotal
		})




